package com.datas.service;

import com.datas.db.hibernatebeans.UmsUser_UmsDepartment;
import com.datas.db.hibernatebeans.UmsUser_UmsDepartment_mng;
import com.datas.db.mappers.UtilMapper;
import com.datas.utils.hbn.HbnTxRuner;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.Session;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by jige0727 on 2016/12/24.
 */
@Service
public class UtilService {
    @Autowired
    UtilMapper mapper;

    /**
     * 刷新管理单位的权限
     *
     * @return
     */
    public JSONObject flushMngDept() {
        return (JSONObject) new HbnTxRuner() {

            @Override
            protected Object dataLogic() throws Exception {
                deleteDeptGLMng(getCurrentSession());//删除之前的关联
                List<UmsUser_UmsDepartment> deptGL = getDeptGL(getCurrentSession());//获取关联 不要总部
                for (UmsUser_UmsDepartment gl : deptGL) {
                    setGLMng(gl, getCurrentSession());//设置管理部门关联
                }
                return new JSONObject().put("res", "finish");
            }
        }.runTx();
    }

    private void setGLMng(UmsUser_UmsDepartment gl, Session session) {
        Integer userid = gl.getUsers_id();
        Set<Integer> deptIds = getDeptIdsInTree(gl.getDepartments_id(), session);//获取这个节点的全部子节点和父节点的id
        for (Integer deptId : deptIds) {
            UmsUser_UmsDepartment_mng mng = new UmsUser_UmsDepartment_mng();
            mng.setUsers_id(userid);
            mng.setDepartments_id(deptId);
            if (!existGlMng(mng, session)) {
                session.save(mng);
                session.flush();
            }
        }
    }

    private Set<Integer> getDeptIdsInTree(Integer deptId, Session session) {
        String struct = "" + session.createQuery("select i.struct from UmsDepartment i where i.id=:id ")
                .setParameter("id", deptId)
                .uniqueResult();
        List<String> structS = session.createQuery("select i.struct from UmsDepartment i " +
                "where i.id=:deptId or i.struct like :struct ")
                .setParameter("deptId", deptId)
                .setParameter("struct", struct + "-%")
                .list();
        Set<Integer> resSet = new HashSet<>();
        for (String stru : structS) {
            for (String id : stru.split("-")) {
                if (StringUtils.isNotBlank(id)) {
                    resSet.add(Integer.parseInt(id));
                }
            }
        }
        return resSet;
    }

    private boolean existGlMng(UmsUser_UmsDepartment_mng mng, Session session) {
        Object count = session.createQuery("select count(*) " +
                "from UmsUser_UmsDepartment_mng i " +
                "where i.users_id=:users_id and i.departments_id=:departments_id ")
                .setParameter("users_id", mng.getUsers_id())
                .setParameter("departments_id", mng.getDepartments_id())
                .uniqueResult();
        return Integer.parseInt("" + count) > 0;
    }

    private List<UmsUser_UmsDepartment> getDeptGL(Session session) {
        return (List<UmsUser_UmsDepartment>) session.createQuery("select i from UmsUser_UmsDepartment i " +
                "inner join UmsDepartment d on d.id=i.departments_id " +
                "where d.struct like '%-%' ").list();
    }

    private void deleteDeptGLMng(Session session) {
        session.createQuery("delete from UmsUser_UmsDepartment_mng").executeUpdate();
        session.flush();
    }
}
